package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.common.constant.RedisConstant;
import com.atguigu.srb.core.listener.ExcelDictDTOListener;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author gcq
 * @since 2021-04-11
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    DictMapper dictMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Transactional(rollbackFor = { Exception.class })
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(dictMapper)).sheet().doRead();
    }

    @Override
    public List<ExcelDictDTO> listDictData() {
        List<Dict> dicts = dictMapper.selectList(null);
        List<ExcelDictDTO> list = new ArrayList<>();
        dicts.forEach(item -> {
            ExcelDictDTO excelDictDTO = new ExcelDictDTO();
            BeanUtils.copyProperties(item, excelDictDTO);
            list.add(excelDictDTO);
        });
        return list;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {
        /**
         * 页面上并不是直接查询出全部的字典数据，而是根据他的一级分类id来进行查询
         * 所以这里是直接更加一级分类Id来进行保存1
         */
        // 首先查询Redis中是否存在数据列表
        try {
            List<Dict> list = (List<Dict>) redisTemplate.opsForValue().get(RedisConstant.SRB_CORE_DICTLIST + parentId);
            if(list != null) {
                return list;
            }
        } catch (Exception e) {
            log.error("Redis服务器异常:" + ExceptionUtils.getStackTrace(e));
        }
        log.debug("从数据库中获取字典列表");
        // 如果存在则从Redis中直接取出然后返回
        // 如果不存在直接去数据库中进行查询
        List<Dict> dictList = dictMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", parentId));
        dictList.forEach(item -> {
            item.setHasChildren(this.hasChildren(item.getId()));
        });
        try {
            log.debug("将数据存入Redis");
            redisTemplate.opsForValue().set(RedisConstant.SRB_CORE_DICTLIST + parentId, dictList);
        } catch (Exception e) {
            log.error("Redis服务器异常:" + ExceptionUtils.getStackTrace(e));
        }
        return dictList;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict_code = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
        return this.listByParentId(dict_code.getId());
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, Integer value) {
        Dict parentDict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
        if(parentDict == null)
        {
            return "";
        }
        Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id", parentDict.getId()).eq("value", value));
        if(dict == null)
        {
            return "";
        }
        return dict.getName();
    }


    private boolean hasChildren(Long id) {
        return baseMapper.selectCount(new QueryWrapper<Dict>().eq("parent_id", id)).intValue() > 0 ? true : false;
    }
}
